package com.cx.service;

import com.cx.property.JedisProperties;
import com.cx.support.SpringContextHolder;
import com.cx.utils.SerializeUtil;
import org.springframework.data.redis.core.*;
import redis.clients.jedis.Jedis;
import redis.clients.util.Pool;

/**
 * Created on 2019-04-18 15:42.
 * @author Alan Shu
 */
public class RedisTemplateAdapter {

    private static SpringContextHolder springContext;

    public static ValueOperations valueOperations(Class clazz) {
        if (SerializeUtil.isStringType(clazz) || SerializeUtil.isCharType(clazz)) {
            return CacheStringTemplate.valueOperations();
        }

        return CacheObjectTemplate.valueOperations();
    }

    public static ListOperations listOperations(Class clazz) {
        if (SerializeUtil.isStringType(clazz) || SerializeUtil.isCharType(clazz)) {
            return CacheStringTemplate.listOperations();
        }

        return CacheObjectTemplate.listOperations();
    }

    public static SetOperations setOperations(Class clazz) {
        if (SerializeUtil.isStringType(clazz) || SerializeUtil.isCharType(clazz)) {
            return CacheStringTemplate.setOperations();
        }
        return CacheObjectTemplate.setOperations();
    }

    public static HashOperations hashOperations(Class clazz) {
        if (SerializeUtil.isStringType(clazz) || SerializeUtil.isCharType(clazz)) {
            return CacheStringTemplate.hashOperations();
        }
        return CacheObjectTemplate.hashOperations();
    }

    public static ZSetOperations zsetOperations(Class clazz) {
        if (SerializeUtil.isStringType(clazz) || SerializeUtil.isCharType(clazz)) {
            return CacheStringTemplate.zsetOperations();
        }
        return CacheObjectTemplate.zsetOperations();
    }

    public static RedisTemplate getRedisTemplate(boolean isStringSerializer) {
        if (isStringSerializer) {
            return CacheStringTemplate.getRedisTemplate();
        }
        return CacheObjectTemplate.getRedisTemplate();
    }

    public static String cacheLevel1Pre(){
        return getJedisProperties().cacheLevel1Pre();
    }

    public static String cacheLevel2Pre(){
        return getJedisProperties().cacheLevel2Pre();
    }

    public static Long cacheLevel1Ttl() {
        return getJedisProperties().getCacheLevel1Ttl();
    }

    public static Long cacheLevel2Ttl() {
        return getJedisProperties().getCacheLevel2Ttl();
    }

    public static JedisProperties getJedisProperties(){
        return springContext.getBean(JedisProperties.class);
    }

    public static Pool<Jedis> getPool() {
        return springContext.getBean(Pool.class);
    }

    public static void init(SpringContextHolder springContext) {
        RedisTemplateAdapter.springContext = springContext;
        CacheStringTemplate.init(springContext);
        CacheObjectTemplate.init(springContext);
    }
}